package edu.xaut.bookingsys.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import edu.xaut.bookingsys.entity.InfoTeacher;
import edu.xaut.bookingsys.service.InfoTeacherService;
import edu.xaut.bookingsys.utils.SecretUtils;
import edu.xaut.bookingsys.utils.SomeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 登录测试
 */
@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    InfoTeacherService infoTeacherService;

    @PostMapping("/login")
    public SaResult login(@RequestParam String id,@RequestParam String pwd) {
        System.out.println("id"+id+"pwd:"+pwd);
        Pair<Boolean, String> validResult = SomeUtils.validTeacherPasswordById(infoTeacherService, id, pwd);

        if (validResult.getKey()) {
            StpUtil.login(id);
            return SaResult.data(StpUtil.getTokenInfo());
        }
        return SaResult.error(StrUtil.format("登录失败：{}", validResult.getValue()));
    }

    @GetMapping("/getPubKey")
    public SaResult getPubKey(@RequestParam String id) {
        String pubKey;
        try {
            pubKey = SecretUtils.genRsaPair(id);
        } catch (Exception e) {
            e.printStackTrace();
            return SaResult.error("PubKey Get Error");
        }
        return SaResult.data(pubKey);
    }

    @GetMapping("/getTeacherInfo")
    public SaResult getTeacherInfo() {

        String teacherId = (String) StpUtil.getLoginId();
        InfoTeacher infoTeacher = infoTeacherService.getById(teacherId);

        if (SaFoxUtil.isEmpty(infoTeacher)) {

            return SaResult.error("用户不存在");
        }
//        infoTeacher.clearPassword();// 将密码置空

        return SaResult.data(infoTeacher);
    }

    @PostMapping("/logout")
    public SaResult logout() {
        // 在logout时删除保存的公钥好像没必要
//        SecretUtils.delRSaPair((String) StpUtil.getLoginId());
        StpUtil.logout();
        return SaResult.ok();
    }

}

